package com.zx.JDK特性.jdk_21;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import org.junit.Test;

public class Main {

    /**
     * 虚拟线程的创建方式，主要有以下 4 种：
     *
     * Thread.startVirtualThread(Runnable task)
     * Thread.ofVirtual().unstarted(Runnable task)
     * Thread.ofVirtual().factory()
     * Executors.newVirtualThreadPerTaskExecutor()
     */
    @Test
    public void test01() {
        // 创建并启动虚拟线程
        Thread.startVirtualThread(() -> {
            System.out.println("Do virtual thread.");
        });
    }

    @Test
    public void test02() {
        // 创建虚拟线程
        Thread vt = Thread.ofVirtual().unstarted(() -> {
            System.out.println("Do virtual thread.");
        });
        // 运行虚拟线程
        vt.start();
    }

    @Test
    public void test03() {
        // 创建虚拟线程工厂
        ThreadFactory tf = Thread.ofVirtual().factory();
        // 创建虚拟线程
        Thread vt = tf.newThread(() -> {
            System.out.println("Do virtual thread.");
        });
        // 运行虚拟线程
        vt.start();
    }

    @Test
    public void test04() {
        // 创建一个支持虚拟线程的线程池
        ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor();
        executor.submit(() -> {
            System.out.println("Do virtual thread.");
        });
    }

}
